package com.nlp.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.*;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.codehaus.jettison.json.JSONObject;

import com.google.common.collect.Maps;

public class SummaryUtils {
	public static String getSummary(String action, String content, 
			String language, String region, String secretkid,
			String timestamp, String version, String secretkey, String ratio) throws Exception {
		/*Map<String, String> docParam = Maps.newHashMap();
		docParam.put("action", action);
		docParam.put("content", content);
		docParam.put("language", language);
		docParam.put("region", region);
		docParam.put("secretid", secretkid);
		docParam.put("timestamp", timestamp);
		docParam.put("version", version);

		String sortDocParam = sortParam(docParam, secretkey);

		String docHex = DigestUtils.md5Hex(sortDocParam);

		docParam.put("signature", docHex);

		JSONObject json = new JSONObject(docParam);
		String postDocParam = json.toString();*/

		return doaaa(content,ratio,language);
		//return sendByPost("http://www.2020nlp.com/apiInfo/summary/", postDocParam);
//		return sendByPost("http://43.240.136.144:9080/v1.0/summary/", postDocParam);
	}

	public static String extractText(InputStream fis, String fileName) throws Exception {
		String text = "";
		if (null == fis) {
			return "";
		}
		HWPFDocument doc = null;
		XWPFWordExtractor extractor = null;
		PDDocument pdDocument = null;
		try {
			if (fileName.toLowerCase().endsWith("doc")) {
				doc = new HWPFDocument(fis);
				StringBuilder doc2 = doc.getText();
				text = doc2.toString();
			} else if (fileName.toLowerCase().endsWith("docx")) {
				XWPFDocument xdoc = new XWPFDocument(fis);
				extractor = new XWPFWordExtractor(xdoc);
				String doc1 = extractor.getText();
				text = doc1;
			} else if (fileName.toLowerCase().endsWith("pdf")) {
				pdDocument = PDDocument.load(fis);
				PDFTextStripper stripper = new PDFTextStripper();
				text = stripper.getText(pdDocument);
			} else {
				return "error file";
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

			if (null != doc) {
				doc.close();
			}

			if (null != extractor) {
				extractor.close();
			}

			if (null != pdDocument) {
				pdDocument.close();
			}
		}
		return text;
	}

	public static String sortParam(Map<String, String> param, String secretkey) {
		List<String> keys = new ArrayList<String>(param.keySet());
		Collections.sort(keys, new Comparator<String>() {

			public int compare(String o1, String o2) {
				char c1 = o1.charAt(0);
				char c2 = o2.charAt(0);
				if (c1 > c2) {
					return 1;
				}
				if (c1 < c2) {
					return -1;
				}
				return 0;
			}

		});

		StringBuffer buf = new StringBuffer();
		for (String key : keys) {
			buf.append(key + "=" + param.get(key) + "&");
		}
		return buf.toString() + secretkey;
	}


	public  static String  doaaa(String cont, String ratio, String language)
	{
		String url = "http://www.2020nlp.com/apiInfo/summary/";
	//	Map<String,String> map = new HashMap<>();
		Map<String, String> map = Maps.newHashMap();

		map.put("apiLang",language);
//		map.put("content","fuck fuck fuck bingbing");
//		System.out.println(cont);
		map.put("content",cont);
		map.put("ratio", ratio);
		try {
			String result = doPost(url,map);
			System.out.println(result);
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		//return "asdfsadfa";
	}
	public static String doPost(String url, Map params){

		BufferedReader in = null;
		try {
			// 定义HttpClient
			HttpClient client = new DefaultHttpClient();
			// 实例化HTTP方法
			HttpPost request = new HttpPost();
			request.setURI(new URI(url));

			//设置参数
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String value = String.valueOf(params.get(name));
				nvps.add(new BasicNameValuePair(name, value));
				//System.out.println(name +"-"+value);
			}
			request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
			HttpResponse response = client.execute(request);
			int code = response.getStatusLine().getStatusCode();
			if(code == 200){    //请求成功
				in = new BufferedReader(new InputStreamReader(response.getEntity()
						.getContent(),"utf-8"));
				StringBuffer sb = new StringBuffer("");
				String line = "";
				String NL = System.getProperty("line.separator");
				while ((line = in.readLine()) != null) {
					sb.append(line + NL);
				}
				in.close();
				return sb.toString();
			}
			else{   //
				System.out.println("状态码：" + code);
				return null;
			}
		}
		catch(Exception e){
			e.printStackTrace();

			return null;
		}
	}



	public static String sendByPost(String urlStr, String param) throws Exception {
		if (StringUtils.isBlank(urlStr) || StringUtils.isBlank(param))
			throw new Exception("url或参数为空");
		String responseContent = "";
		try {
			PostMethod method = new PostMethod(urlStr);
			Header header = new Header();
			header.setName("Content-Type");
			header.setValue("application/json");
			RequestEntity entity = new StringRequestEntity(param, "application/json", "UTF-8");
			method.setRequestEntity(entity);
			method.addRequestHeader(header);
			int rst = HttpClientManager.getHttpClient().executeMethod(method);
			if (rst == HttpStatus.SC_OK) {
				InputStream in = method.getResponseBodyAsStream();
				BufferedReader rd = new BufferedReader(new InputStreamReader(in, "utf-8"));
				String tempLine = rd.readLine();				
				StringBuffer tempStr = new StringBuffer();
				String crlf = System.getProperty("line.separator");
				while (tempLine != null) {
					tempStr.append(tempLine);
					tempStr.append(crlf);
					tempLine = rd.readLine();
				}
				responseContent = tempStr.toString();
				System.out.println(responseContent);
				rd.close();
				in.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return responseContent;
	}

	public static String intToRoman(int num) {
		String M[] = { "", "M", "MM", "MMM" };
		String C[] = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" };
		String X[] = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" };
		String I[] = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" };
		return M[num / 1000] + C[(num % 1000) / 100] + X[(num % 100) / 10] + I[(num % 10)];
	}
}
